package com.yunzai.file.service.impl;

import com.yunzai.file.config.FileDownloadConfig;
import com.yunzai.file.config.FileUploadConfig;
import com.yunzai.file.service.IFileUploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements IFileUploadService {

    @Autowired
    private FileUploadConfig fileUploadConfig;

    public String uploadFile(MultipartFile file) {
        String path = fileUploadConfig.getStorage().getPath();
        String tempPath = fileUploadConfig.getStorage().getTempDir();
        return upload(file, path, tempPath);
    }

    public String uploadAvatar(MultipartFile file) {
        String path = fileUploadConfig.getStorage().getAvatarPath();
        String tempPath = fileUploadConfig.getStorage().getTempDir();
        return upload(file, path, tempPath);
    }

    private String upload(MultipartFile file, String path, String tempPath) {
        // 使用配置参数
        long maxSize = fileUploadConfig.getMaxSizeInBytes();
        if (file.getSize() > maxSize) {
            throw new IllegalArgumentException("上传文件超出" + fileUploadConfig.getLimits().getMaxSize());
        }

        // 检查文件类型
        String rawType = file.getContentType();
        // 获取并清理MIME类型
        String contentType = "";
        if (rawType != null) contentType = rawType.split(";")[0].trim().toLowerCase();
        // 执行类型校验
        if (!fileUploadConfig.isMimeTypeAllowed(contentType)) {
            throw new IllegalArgumentException("不支持当前文件类型: " + contentType);
        }

        path = path.endsWith("/") ? path : path + "/";
        tempPath = tempPath.endsWith("/") ? tempPath : tempPath + "/";
        // 确保目录存在
        try {
            Files.createDirectories(new File(path).toPath());
            Files.createDirectories(new File(tempPath).toPath());
        } catch (IOException e) {
            throw new RuntimeException("无法创建存储目录", e);
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String[] split = originalFilename.split("\\.");
        String suffix = split[split.length - 1];
        String fileName = originalFilename.substring(0, originalFilename.length() - suffix.length() - 1) + "_" + new Date().getTime() + "." + suffix;
        Path targetPath = new File(path + "/" + fileName).toPath();

        // 保存文件
        try {
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败", e);
        }
        return fileName;
    }

}
